package com.example.dense_rack_server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.dense_rack_server.entity.MyRoleUser;
import com.example.dense_rack_server.entity.MyUser;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dense_rack_server.entityVo.MyDeptTreeVo;
import com.example.dense_rack_server.entityVo.MyUserVo;
import com.example.dense_rack_server.mapper.MyDeptMapper;
import com.example.dense_rack_server.mapper.MyRoleUserMapper;
import com.example.dense_rack_server.mapper.MyUserMapper;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.utils.DateFormat;
import com.example.dense_rack_server.utils.ResponseModel;
import com.example.dense_rack_server.utils.TreeUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author  张彬 
 * @since 2025-03-03
 */
@Service
public class MyUserService extends ServiceImpl<MyUserMapper, MyUser> {

    @Resource
    private MyUserMapper myUserMapper;
    @Resource
    private MyRoleUserMapper myRoleUserMapper;
    @Resource
    private MyDeptMapper myDeptMapper;

    /**
     * 根据用户名获取用户
     */
    public MyUser getUserByName(String userName) {
        return myUserMapper.getUserByName(userName);
    }

    /**
     * 绘制用户树
     */
    public Map<String, Object> buildDept() {
        List<MyDeptTreeVo> myDeptTreeVoList = myDeptMapper.buildDept();
        List<MyDeptTreeVo> resultList = TreeUtil.buildDeptAll(myDeptTreeVoList);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("message", 200);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", map);
        resultMap.put("data", resultList);
        return resultMap;
    }

    /**
     * 获取用户列表
     */
    public Map<String, Object> userList(String user_name, String nick_name, String deptId, String status, int page, int limit) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isEmpty(deptId)) {
            if (StrUtil.isNotEmpty(user_name)) {
                paramsMap.put("user_name", user_name);
            }
            if (StrUtil.isNotEmpty(nick_name)) {
                paramsMap.put("nick_name", nick_name);
            }
            if (StrUtil.isNotEmpty(status)) {
                paramsMap.put("status", status);
            }
            List<Map<String, Object>> mapList = myUserMapper.getAllUser(paramsMap);
            map.put("count", myUserMapper.getAllUserCount(paramsMap));
            map.put("data", mapList);
        } else {
            paramsMap.put("deptId", deptId);
            List<Map<String, Object>> mapList = myUserMapper.getDeptUser(paramsMap);
            map.put("data", mapList);
            map.put("count", myUserMapper.getDeptUserCount(deptId));
        }
        return map;
    }

    /**
     * 新增用户
     */
    public ResponseModel saveUser(MyUserVo myUserVo) {
        // 添加用户信息
        myUserVo.setStatus(myUserVo.getStatus());
        myUserVo.setCreateTime(DateFormat.getTime());
        myUserVo.setUpdateTime(DateFormat.getTime());
        myUserVo.setLoginMethod(1);
        int status = myUserMapper.insert(myUserVo);
        if (status > 0) {
            // 添加用户和角色表依赖
            MyRoleUser myRoleUser = new MyRoleUser();
            myRoleUser.setRoleId(Convert.toInt(myUserVo.getRoleId()));
            myRoleUser.setUserId(myUserVo.getUserId());
            myRoleUserMapper.save(myRoleUser);
            //添加日志记录
//            JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            MyUserLogInsert.insert(1, jwtUserDto.getUsername() + "新增" + myUserVo.getUserName() + "用户");
            return ResponseModel.success("用户添加成功");
        } else {
            return ResponseModel.fail("用户添加失败");
        }
    }


    /**
     * 执行用户数据修改
     */
    public ResponseModel editUser(JSONObject data) {
        //1.先修改用户信息
        data.set("user_id", data.getInt("user_id"));
        data.set("update_time", DateUtil.now());
        data.set("status", data.getBool("status"));
        if (StrUtil.isNotEmpty(data.getStr("password"))) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            data.set("password", bCryptPasswordEncoder.encode(data.getStr("password")));
        }
        myUserMapper.updateUser(data);
        //2.修改角色信息
        MyRoleUser myRoleUser = new MyRoleUser();
        myRoleUser.setUserId(data.getInt("user_id"));
        myRoleUser.setRoleId(data.getInt("roleId"));
        myRoleUserMapper.updateById(myRoleUser);
        //添加日志记录
//        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        MyUserLogInsert.insert(2, jwtUserDto.getUsername() + "修改" + data.getStr("userName") + "用户");
        return ResponseModel.success("用户修改成功");
    }

    /**
     * 修改用户状态
     */
    public ResponseModel changeStatus(JSONObject data) {
        UpdateWrapper<MyUser> myUserUpdateWrapper = new UpdateWrapper<>();
        //条件构造器Set方法
        //假设只更新一个字段在使用updateWrapper 的构造器中也需要构造一个实体对象,这样比较麻烦。可以使用updateWrapper的set方法
        myUserUpdateWrapper.eq("user_id", data.getInt("userId")).set("status", data.getBool("status"));
        int count = myUserMapper.update(null, myUserUpdateWrapper);
        if (count > 0) {
            if (data.getInt("status") == 0) {
                return ResponseModel.success("禁用成功");
            } else {
                return ResponseModel.success("启用成功");
            }
        } else {
            return ResponseModel.fail("请求失败");
        }
    }

    /**
     * 删除用户
     */
    public ResponseModel deleteUser(String user_id) {
        String[] strings = user_id.split(",");
        List<String> idList = CollUtil.newArrayList(strings);
        List<MyUser> myUserList = myUserMapper.selectBatchIds(idList);
        StringBuilder userNames = new StringBuilder();
        for (MyUser myUser : myUserList) {
            MyUser lastMyUser = myUserList.get(myUserList.size() - 1);
            if (!lastMyUser.getUserName().equals(myUser.getUserName())) {
                userNames.append(myUser.getUserName()).append(",");
            } else {
                userNames.append(myUser.getUserName());
            }
        }
        int delCount = myUserMapper.deleteBatchIds(idList);
        if (delCount > 0) {
//            JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            MyUserLogInsert.insert(3, jwtUserDto.getUsername() + "删除" + userNames.toString() + "用户");
            return ResponseModel.success("删除成功");
        } else {
            return ResponseModel.fail("删除失败,请重新尝试");
        }
    }

    /**
     * 用户详情
     */
    public ModelAndView userDetail(String user_id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/user_detail");
        Map<String, Object> map = myUserMapper.getUserDetail(user_id);
        modelAndView.addAllObjects(map);
        return modelAndView;
    }

    /**
     * 修改密码
     */
    public ModelAndView changePwd() {
        ModelAndView modelAndView = new ModelAndView();
        // 获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userId = jwtUserDto.getMyUser().getUserId();
        Map<String, Object> userMap = myUserMapper.getUserDetail(userId.toString());
        modelAndView.addAllObjects(userMap);
        modelAndView.setViewName("changePwd");

        Map<String, Object> roleMap = myUserMapper.getUserRoleName(userMap.get("user_name").toString());
        modelAndView.addAllObjects(roleMap);
        return modelAndView;
    }

}
